package com.example.shangjiba;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

public class MineFragment extends Fragment {

    private ImageView ivAvatar;
    private TextView tvUsernameDisplay;
    private TextView tvInterest;
    private Button btnSelectInterest;
    private Button btnMyBooks;
    private Button btnLogout;
    private SharedPreferences sharedPreferences;
    private ActivityResultLauncher<Intent> interestLauncher;
    private ActivityResultLauncher<String> pickImageLauncher;
    private ActivityResultLauncher<String> requestPermissionLauncher;
    private BroadcastReceiver interestReceiver;
    
    private AvatarManager avatarManager;
    private String currentUserEmail;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, container, false);
        
        initViews(view);
        initData();
        initLaunchers();
        setupListeners();
        loadUserInfo();
        loadAvatar();
        registerBroadcast();
        
        return view;
    }
    
    private void initViews(View view) {
        ivAvatar = view.findViewById(R.id.iv_avatar);
        tvUsernameDisplay = view.findViewById(R.id.tv_username_display);
        tvInterest = view.findViewById(R.id.tv_interest);
        btnSelectInterest = view.findViewById(R.id.btn_select_interest);
        btnMyBooks = view.findViewById(R.id.btn_my_books);
        btnLogout = view.findViewById(R.id.btn_logout);
    }
    
    private void initData() {
        sharedPreferences = requireActivity().getSharedPreferences("UserData", Context.MODE_PRIVATE);
        currentUserEmail = sharedPreferences.getString("username", "");
        avatarManager = new AvatarManager(requireContext());
    }
    
    private void initLaunchers() {
        // 兴趣选择Launcher
        interestLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == android.app.Activity.RESULT_OK && result.getData() != null) {
                    String interest = result.getData().getStringExtra("interest");
                    if (interest != null && !interest.isEmpty()) {
                        sharedPreferences.edit().putString("interest", interest).apply();
                        tvInterest.setText("当前兴趣：" + interest);
                        
                        Intent broadcastIntent = new Intent("com.example.shangjiba.INTEREST_UPDATED");
                        requireActivity().sendBroadcast(broadcastIntent);
                    }
                }
            }
        );
        
        // 图片选择Launcher
        pickImageLauncher = registerForActivityResult(
            new ActivityResultContracts.GetContent(),
            uri -> {
                if (uri != null) {
                    handleImageResult(uri);
                } else {
                    Toast.makeText(requireContext(), "未选择图片", Toast.LENGTH_SHORT).show();
                }
            }
        );
        
        // 权限请求Launcher
        requestPermissionLauncher = registerForActivityResult(
            new ActivityResultContracts.RequestPermission(),
            isGranted -> {
                if (isGranted) {
                    openImagePicker();
                } else {
                    showPermissionDeniedDialog();
                }
            }
        );
    }
    
    private void setupListeners() {
        // 头像点击事件
        ivAvatar.setOnClickListener(v -> requestImagePicker());
        
        // 选择兴趣按钮
        btnSelectInterest.setOnClickListener(v -> {
            Intent intent = new Intent(requireActivity(), InterestSelectActivity.class);
            interestLauncher.launch(intent);
        });
        
        // 我的书籍按钮
        btnMyBooks.setOnClickListener(v -> {
            Intent intent = new Intent(requireActivity(), BookListActivity.class);
            startActivity(intent);
        });
        
        // 退出登录按钮
        btnLogout.setOnClickListener(v -> showLogoutDialog());
    }
    
    private void registerBroadcast() {
        interestReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                loadUserInfo();
            }
        };
        
        IntentFilter filter = new IntentFilter("com.example.shangjiba.INTEREST_UPDATED");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            requireActivity().registerReceiver(interestReceiver, filter, Context.RECEIVER_NOT_EXPORTED);
        } else {
            requireActivity().registerReceiver(interestReceiver, filter);
        }
    }

    private void loadUserInfo() {
        String username = sharedPreferences.getString("username", "");
        String interest = sharedPreferences.getString("interest", "未选择");
        
        if (interest.isEmpty()) {
            interest = "未选择";
        }
        
        tvUsernameDisplay.setText("用户邮箱：" + username);
        tvInterest.setText("当前兴趣：" + interest);
    }
    
    /**
     * 请求打开图片选择器
     */
    private void requestImagePicker() {
        // Android 13及以上不需要READ_EXTERNAL_STORAGE权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            openImagePicker();
            return;
        }
        
        // Android 13以下需要检查权限
        if (ContextCompat.checkSelfPermission(requireContext(), 
                Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            openImagePicker();
        } else {
            showPermissionRationaleDialog();
        }
    }
    
    /**
     * 显示权限说明对话框
     */
    private void showPermissionRationaleDialog() {
        new AlertDialog.Builder(requireContext())
                .setTitle("需要存储权限")
                .setMessage("需要存储权限以选择图片\n\n此权限仅用于选择头像，不会访问其他文件")
                .setPositiveButton("授权", (dialog, which) -> {
                    requestPermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE);
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    /**
     * 显示权限被拒绝对话框
     */
    private void showPermissionDeniedDialog() {
        new AlertDialog.Builder(requireContext())
                .setTitle("无法选择图片")
                .setMessage("已拒绝存储权限\n\n如需更换头像，请在系统设置中手动开启权限")
                .setPositiveButton("确定", null)
                .show();
    }
    
    /**
     * 打开图片选择器
     */
    private void openImagePicker() {
        try {
            pickImageLauncher.launch("image/*");
        } catch (Exception e) {
            Toast.makeText(requireContext(), "无法打开相册", Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 处理选择的图片
     */
    private void handleImageResult(Uri uri) {
        try {
            boolean success = avatarManager.saveAvatar(currentUserEmail, uri);
            if (success) {
                loadAvatar();
                Toast.makeText(requireContext(), "头像更换成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(requireContext(), "头像保存失败，请重试", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Toast.makeText(requireContext(), "图片处理失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 加载头像
     */
    private void loadAvatar() {
        if (currentUserEmail == null || currentUserEmail.isEmpty()) {
            return;
        }
        
        Bitmap avatar = avatarManager.loadAvatar(currentUserEmail);
        if (avatar != null) {
            ivAvatar.setImageBitmap(avatar);
            // 设置圆形裁剪
            ivAvatar.setClipToOutline(true);
            ivAvatar.setBackground(null);
        } else {
            ivAvatar.setImageResource(R.drawable.default_avatar);
        }
    }
    
    /**
     * 显示退出登录对话框
     */
    private void showLogoutDialog() {
        new AlertDialog.Builder(requireActivity())
                .setTitle("确认退出")
                .setMessage("是否确认退出登录？")
                .setPositiveButton("确定", (dialog, which) -> {
                    sharedPreferences.edit().clear().apply();
                    
                    Intent loginIntent = new Intent(requireActivity(), LoginActivity.class);
                    loginIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(loginIntent);
                    requireActivity().finish();
                })
                .setNegativeButton("取消", null)
                .show();
    }

    @Override
    public void onResume() {
        super.onResume();
        // 每次回到前台时更新用户信息和头像
        loadUserInfo();
        loadAvatar();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 注销广播接收器
        if (interestReceiver != null) {
            requireActivity().unregisterReceiver(interestReceiver);
        }
    }
}
